import httpx
import os
from pathlib import Path

def download_file(url: str, save_path: str, chunk_size: int = 1024 * 1024) -> bool:
    """
    使用 httpx 从指定 URL 下载文件到本地路径
    
    :param url: 要下载的文件 URL
    :param save_path: 本地保存路径（包含文件名）
    :param chunk_size: 流式下载的分块大小（默认 1MB）
    :return: 下载成功返回 True，失败返回 False
    """
    try:
        # 确保保存目录存在
        save_dir = Path(save_path).parent
        if not save_dir.exists():
            save_dir.mkdir(parents=True, exist_ok=True)

        with httpx.stream("GET", url) as response:
            # 检查 HTTP 状态码
            response.raise_for_status()
            
            # 获取文件总大小（如果有）
            total_size = int(response.headers.get("content-length", 0))
            
            with open(save_path, "wb") as f:
                downloaded = 0
                for chunk in response.iter_bytes(chunk_size=chunk_size):
                    f.write(chunk)
                    downloaded += len(chunk)
                    # 可选：这里可以添加进度显示逻辑（需配合 tqdm 等库）
                    # print(f"下载进度: {downloaded / total_size * 100:.2f}%") if total_size else None

            print(f"文件下载完成，保存至: {os.path.abspath(save_path)}")
            return True

    except httpx.HTTPStatusError as e:
        print(f"HTTP 错误: {e.response.status_code} - {e}")
    except httpx.RequestError as e:
        print(f"网络请求失败: {e}")
    except Exception as e:
        print(f"下载过程中发生未知错误: {e}")
    return False

if __name__ == "__main__":
    # 示例下载（可替换为实际 URL）
    test_url = "https://halostar-server.oss-cn-shanghai.aliyuncs.com/2j5BP0jfOMbS0e50edf9941f8c580642bc002dd4004d.jpg"  # 随机示例图片
    save_path = "aaa.jpg"   # 本地保存路径
    
    if download_file(test_url, save_path):
        print("下载成功！")
    else:
        print("下载失败")
    